/* 
 * 首页相关操作的js,需要依赖jQuery以及百度地图API
 */
//站点地址,由于动态生成页面的缘故,无法采用相对路径,
//所以通过setUrl()设置站点地址后,再有此地址生成各个页面的地址
var site_url = "";
//全局地图
var map;
//保存各个位置的消息的HashMap，每个地点是一个Key，用经纬度标识
var mark_list = new HashMap();

//一些常量
var PLACE_INTERESTING = "景点";
var PLACE_RESTAURANTS = "餐馆";

//设置站点地址
function setUrl(url)
{
	site_url = url;
}

//加载地图
function loadMap(container)
{
	map = new BMap.Map(container);
	showCurrentCity();		//直接跳到当前城市
	map.enableScrollWheelZoom();

    map.addControl(new BMap.NavigationControl());
    map.addControl(new BMap.ScaleControl());
    map.addControl(new BMap.OverviewMapControl());
    map.addControl(new BMap.MapTypeControl());
	
    refresh();
}

/**
 *显示当前城市
 **/
function showCurrentCity()
{
	function myFun(result){
		var poi = result.center;
		map.centerAndZoom(poi, 12);
	}
	
	var myCity = new BMap.LocalCity();
	myCity.get(myFun);
}

//刷新
function refresh()
{
   url = site_url + "index.php?app=geoweibo&ac=do&ts=search";
   //alert(url);
   $.post(
       url,
       null,
       function(data,status){
		   //alert(data + "," + status);
           if("success" == status)
           {
			   //alert(data);
               check_ret(data);
           }
       }
   );
}

//处理请求返回
function check_ret(data)
{
    var json = eval("(" + data + ")");
    var ret = json.ret;

    if("success" == ret)
    {
        var loc_list = json.record_list;
        add_geoweibos(loc_list);
    }
    else
    {
        alert("Error : " + data);
    }
}

//添加一组标注点
function add_geoweibos(arr)
{
    for(i = 0; i < arr.length; i++)
    {
		var geoweibo = arr[i];
        add_geoweibo(geoweibo);
    }
}

//添加一个标注点
function add_marker(point)
{
    var marker = new BMap.Marker(point);
    map.addOverlay(marker);
    return marker;
}

//信息窗口相关定义
var INFO_WINDOW_DEFAULT_WIDTH = 350;					//默认宽度

var INFO_WINDOW_COMMENT_HEIGHT = 200;					//comment元素高度
var INFO_WINDOW_COMMENT_HEIGHT_NO_CMT = 70;				//没有评论时的元素高度

var INFO_WINDOW_DEFAULT_HEIGHT = 210;					//默认高度
var INFO_WINDOW_OPEN_COMMENT_HEIGHT = 400;				//评论展开后高度
var INFO_WINDOW_OPEN_COMMENT_HEIGHT_NO_CMT = 300;		//没有评论时评论展开后的高度

var INFO_WINDOW_DEFAULT_HEIGHT_NO_PIC = 110;			//默认高度，无图片
var INFO_WINDOW_OPEN_COMMENT_HEIGHT_NO_PIC = 300;		//评论展开后高度，无图片
var INFO_WINDOW_OPEN_COMMENT_HEIGHT_NO_CMT_NO_PIC = 200;//评论展开后高度，无图片

//将地点信息添加到Mark HashMap里
//返回值: true - 新增marker; false - 已存在marker;
function add_to_hashMap(geoweibo)
{
	var str = "(" + geoweibo.latitude + "," + geoweibo.longtitude + ")";
	var ret;
	var arr;
	if(mark_list.containsKey(str)) {
		arr = mark_list.get(str);
		arr.push(geoweibo);
		ret = false;
	} else {
		arr = new Array();
		arr.push(geoweibo);
		mark_list.put(str, arr);
		ret = true;
	}
	
	return ret;
}

//得到某条微博的具体html内容
function get_oneMsg_sContent(geoweibo)
{
	//读取各个信息
	var id = geoweibo.id;
	var msg = geoweibo.msg;
	var photo = geoweibo.photo;
	var comment_count = geoweibo.comment_count;
	var userid = geoweibo.userid;
	var username = geoweibo.username;
	var uptime = geoweibo.uptime;
	var face_url = geoweibo.faceUrl;

	//附带图片的内容
	var photo_content = "";
	if(photo != null) {
		var photo_url = site_url + "uploadfile/geoweibo_photo/" + photo;
		photo_content = "<a id='imgbox' href='" + photo_url + "'><img id='imgDemo' src='" + photo_url + "' height='104'/></a>";
	}

	//头像的url
	var user_space_url = site_url + "index.php?app=user&ac=space&id=" + userid;

	//更新时间
	var uptime_t = getDateString(uptime);

	//消息内容
	var sMessage =  "<div class='weibo_face'>" +
						"<a target='_blank' href='" + user_space_url + "'>" +
							"<img src='"+ face_url +"'>"+
						"</a>"+
					"</div>" +
					"<div class='weibo_detail'>" +
						"<div class='weibo_info'>" + "<a class='weibo_name' target='_blank' href='" + user_space_url + "'>" + username + "</a>" + "</div>" +
						"<div class='weibo_text'>" + msg + "</div>" +
						"<div class='weibo_pic' id='weibo_pic'>" + photo_content + "</div>" +
						"<div class='weibo_func clearfix'>" +
							"<div class='weibo_handle'>" +
							"<a id='info_comment_btn' href='#' onClick='togle_comment("+ id + "," + comment_count +")'>评论(" + comment_count + ")</a>" +
							"</div>" +
							"<div class='weibo_from'>" + uptime_t +"</div>" +
						"</div>" +
					"</div>";

	//评论的div内容
	var sComment = "<div class='weibo_comment' id='comment'>" +
						"<div class='comment_input'>" +
							"<form method='POST' action='./index.php?app=geoweibo&ac=do&ts=comment'>" +
								"<input type='hidden' name='geoweibo_id' value='" + id + "' />" +
								"<textarea name='content'></textarea>" +
								"<input type='submit' id='comment_submit' value='提交'/>" +
							"</form>" +
						"</div>" +

						"<div class='comment_list'>" +
							"<table id='comment_table'>" +
							"</table>" +
						"</div>" +
					"</div>";

	var sContent = "<div class='weibo_feed_detail s_line clearfix'>" + sMessage + sComment + "</div>";
	
	return sContent;
}

//得到某个地点一组微博的具体html内容
function get_multiMsg_sContent(str)
{
	var arr = mark_list.get(str);
	if(arr == null || arr.length == 0) {
		alert("Error : Can't find geoweibo on this mark!");
		return "";
	}
	
	var sContent = "<div class='multi_msg_list'><table>";
	for(i = 0; i < arr.length; i++) {
		var geoweibo = arr[i];
		var id = geoweibo.id;
		var face_url = geoweibo.faceUrl;
		var username = geoweibo.username;
		var photo = geoweibo.photo;
		var msg = geoweibo.msg;
		var uptime = geoweibo.uptime;

		var uptime_t = getDateString(uptime);
		var photo_content = "";
		//显示是否带有图片的小图标
		if(photo != null) {
			photo_content = "<img src='" + site_url + "public/images/pic.png" + "' height='15'/>";
		}

		sContent += "<tr onclick='open_detailMsgBox(" + id + ',"' + str + '"' + ")'>" + 
						"<td class='multi_msg_face_td'>" + "<img src='" + face_url + "'/>" + "</td>" +
						"<td>" + username + ": " + msg + 
							"</br>" +
							photo_content + " (" + uptime_t + ")" + 
						"</td>" +
					"</tr>";
	}
	sContent += "</table></div>";
	
	return sContent;
}

//点击某个marker时打开InfoWindow
function open_InfoWindowForMarker(marker)
{
	var p = marker.getPosition();
	var str = "(" + p.lat + "," + p.lng + ")";
	
	var arr = mark_list.get(str);
	if(arr == null || arr.length == 0) {
		alert("Error : Can't find geoweibo on this mark!");
		return;
	}
	
	//判断是一条微博还是多条
	var multiMsg = false;
	if(arr.length == 1) {
		multiMsg = false;
	} else {
		multiMsg = true;
	}
	
	var infoWindow;
	var sContent;
	var geoweibo;
	
	//根据不同模式显示不同内容
	if(multiMsg) {
		sContent = get_multiMsg_sContent(str);
		
		infoWindow = new BMap.InfoWindow(sContent);
		infoWindow.setWidth(INFO_WINDOW_DEFAULT_WIDTH);
		infoWindow.addEventListener("open", onInfoWindowOpen);
		//infoWindow.addEventListener("close", onInfoWindowClose);
		
		marker.openInfoWindow(infoWindow);
		
		startLocalSearch(p, PLACE_INTERESTING);
	} else {
		geoweibo = arr[0];

		sContent = get_oneMsg_sContent(geoweibo);

		infoWindow = new BMap.InfoWindow(sContent);
		infoWindow.setWidth(INFO_WINDOW_DEFAULT_WIDTH);
		infoWindow.addEventListener("open", onInfoWindowOpen);
		//infoWindow.addEventListener("close", onInfoWindowClose);

		marker.openInfoWindow(infoWindow);

		$("a#imgbox").fancybox({
			'transitionIn'	: 'none',
			'transitionOut'	: 'none'
		});

		startLocalSearch(p, PLACE_INTERESTING);
	}
}

//打开某条详细信息
function open_detailMsgBox(id, marker)
{
	var arr = mark_list.get(marker);
	if(arr == null || arr.length == 0) {
		alert("Error : Can't find geoweibo on this mark!");
		return;
	}
	
	var geoweibo = null;
	var i = 0;
	for(i = 0; i < arr.length; i++) {
		if(arr[i].id == id) {
			geoweibo = arr[i];
			break;
		}
	}
	if(geoweibo == null) {
		alert("Error : Can't find geoweibo for id :" + id);
		return;
	}
	
	//构造header内容
	var content = "<div class='weibo_header'><a onclick='open_MsgList(" + '"' + marker + '"' + ")'>返回列表</a>  ";
	//第一条以外添加上一条 
	if(i > 0) {
		content = content + "<a onclick='open_detailMsgBox(" + arr[i - 1].id + ',"' + marker + '"' + ")'><img class='pointer_img' src='" + site_url + "public/images/pointer_left.png" + "' /></a>"
	} else {
		content = content + "<img class='pointer_img_invalid' src='" + site_url + "public/images/pointer_left_invalid.png" + "' />";
	}
	//加点间隔
	content = content + "    ";
	//最后一条以外添加下一条
	if(i < (arr.length - 1)) {
		content = content + "<a onclick='open_detailMsgBox(" + arr[i + 1].id + ',"' + marker + '"' + ")'><img class='pointer_img' src='" + site_url + "public/images/pointer_right.png" + "' /></a>"
	} else {
		content = content + "<img class='pointer_img_invalid' src='" + site_url + "public/images/pointer_right_invalid.png" + "' />";
	}
	content = content + "</div>";
	//构造主题内容
	content = content + get_oneMsg_sContent(geoweibo);
	
	currentInfoWindow.setContent(content);
	currentInfoWindow.redraw();
	
	$("a#imgbox").fancybox({
			'transitionIn'	: 'none',
			'transitionOut'	: 'none'
	});
		
	return;
}

function open_MsgList(marker)
{	
	var content = get_multiMsg_sContent(marker);
	currentInfoWindow.setContent(content);
	currentInfoWindow.redraw();
	
	return;
}

//添加信息窗口
function add_geoweibo(geoweibo)
{
	if(add_to_hashMap(geoweibo)) {
		var longtitude = geoweibo.longtitude;
		var latitude = geoweibo.latitude;
		var point = new BMap.Point(longtitude, latitude);
		var marker = add_marker(point);

		var openInfoFunc = function(){
			open_InfoWindowForMarker(marker);
		};

		marker.addEventListener("click", openInfoFunc);
	}
	
    return;
}

//当前信息窗口
var currentInfoWindow;

function onInfoWindowOpen(e)
{
	currentInfoWindow = e.target;
}

function onInfoWindowClose(e)
{
	
}


//显示/隐藏评论框
function togle_comment(id, comment_count)
{
	var cmt = $("#comment");
	
	if(cmt.is(":visible")) {		//隐藏评论框
		cmt.hide();
	} else {		//显示评论框
		cmt.show();
		get_comment(id);
		var h1 = INFO_WINDOW_COMMENT_HEIGHT;
		if(comment_count > 0) {
			h1 = INFO_WINDOW_COMMENT_HEIGHT;
		} else {
			h1 = INFO_WINDOW_COMMENT_HEIGHT_NO_CMT;
		}
		cmt.height(h1);
	}
	
	currentInfoWindow.redraw();
}

//读取评论
function get_comment(id)
{
	url = site_url + "index.php?app=geoweibo&ac=do&ts=comment_search";
    $.post(
       url,
       {
		   geoweibo_id : id
       },
       function(data,status){
           if("success" == status)
           {
               ret_comment(data);
           }
       }
    );
}

//检查评论返回
function ret_comment(data)
{
	var json = eval("(" + data + ")");
    var ret = json.ret;

    if("success" == ret)
    {
        var comment_list = json.record_list;
        add_comment_to_list(comment_list);
    }
    else
    {
        alert("Error : " + data);
    }
}

//将评论放到界面上
function add_comment_to_list(arr)
{
	var list = $("#comment_table");	
	list.empty();
	
	for(i = 0; i < arr.length; i++)
    {
		var userid = arr[i].userid;
		var username = arr[i].username;
		var comment = arr[i].comment;
        var addtime = arr[i].addtime;
		var display_time = getDateString(addtime);
		var face_url = arr[i].faceUrl;
		
		var user_space_url = site_url + "./index.php?app=user&ac=space&id=" + userid;
		
        var str = "<tr>" + 
					"<td class='comment_face_td'>" + "<a target='_blank' href='" + user_space_url + "'>" + "<img src='" + face_url + "'/>" + "</a>" +"</td>" +
					"<td>" + 
						"<a target='_blank' href='" + user_space_url + "'>" + username + "</a>" + ": " + comment + 
						"<br />" +
						" (" + display_time + ")" + 
					"</td>" +
				  "</tr>";
		list.append(str);
    }
}


//当前景点附近搜索信息
var mLocalSearch;
//当前显示圆圈
var mCurrentLocalCircle;

/**
 *在某个点附近搜索景点
 **/
function startLocalSearch(point, type)
{
	resetLocalSearch();
	mCurrentLocalCircle = new BMap.Circle(point,1000,{fillColor:"blue", strokeWeight: 1 ,fillOpacity: 0.3, strokeOpacity: 0.3});
    map.addOverlay(mCurrentLocalCircle);
    mLocalSearch =  new BMap.LocalSearch(map, {renderOptions: {map: map, autoViewport: false, selectFirstResult: false}});  
    var bounds = getSquareBounds(mCurrentLocalCircle.getCenter(),mCurrentLocalCircle.getRadius());
    mLocalSearch.searchInBounds(type,bounds); 
}

/**
 *关闭搜索及圆圈显示
 **/
function resetLocalSearch()
{
	if(mLocalSearch != null) {
		mLocalSearch.clearResults();
	}
	if(map != null && mCurrentLocalCircle != null) {
		map.removeOverlay(mCurrentLocalCircle);
	}
}
/**
* 得到圆的内接正方形bounds
* @param {Point} centerPoi 圆形范围的圆心
* @param {Number} r 圆形范围的半径
* @return 无返回值   
* 来自：百度API示例
*/ 
function getSquareBounds(centerPoi,r){
   var a = Math.sqrt(2) * r; //正方形边长

   mPoi = getMecator(centerPoi);
   var x0 = mPoi.x, y0 = mPoi.y;

   var x1 = x0 + a / 2 , y1 = y0 + a / 2;//东北点
   var x2 = x0 - a / 2 , y2 = y0 - a / 2;//西南点

   var ne = getPoi(new BMap.Pixel(x1, y1)), sw = getPoi(new BMap.Pixel(x2, y2));
   return new BMap.Bounds(sw, ne);        

}
//根据球面坐标获得平面坐标。
//来自：百度API示例
function getMecator(poi){
   return map.getMapType().getProjection().lngLatToPoint(poi);
}
//根据平面坐标获得球面坐标。
//来自：百度API示例
function getPoi(mecator){
   return map.getMapType().getProjection().pointToLngLat(mecator);
}
